﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using System.Text.RegularExpressions;

namespace XSTDZ.ERP.WebApp.Models
{
    /// <summary>
    /// 业务单据 单号生成器
    /// </summary>
    public class BusinessBillNoCreator
    {
        IRefeService billImpl = ServiceLocator.Instance.GetService<IRefeService>();
        private readonly object obj = new object();
        
        public BusinessBillNoCreator()
        {
        
        }

        /// <summary>
        /// 创建发货单号
        /// </summary>
        /// <returns></returns>
        public string CreateDeliveryNextNO()
        { 
            //IProductDeliveryBillService billImpl = ServiceLocator.Instance.GetService<IProductDeliveryBillService>();
            //return CreateBillNO(SystemConfig.DeliveryBillNOFormate, billImpl.GetMaxBillNo());//获得 单号
            return GetNextNO(SystemConfig.DeliveryBillNOFormate);
        }
        /// <summary>
        /// 入库单单号生成
        /// </summary>
        /// <returns></returns>
        public string CreateInNextNO()
        {
            //IProductInService billImpl = ServiceLocator.Instance.GetService<IProductInService>();
            //return CreateBillNO(SystemConfig.InBillNOFormate, billImpl.GetMaxBillNo());//获得 单号

            return GetNextNO(SystemConfig.InBillNOFormate);
        }
        /// <summary>
        /// 盘点单单号生成
        /// </summary>
        /// <returns></returns>
        public string CreateCheckNextNO()
        {
            //IProductCheckService billImpl = ServiceLocator.Instance.GetService<IProductCheckService>();
            //return CreateBillNO(SystemConfig.CheckBillNOFormate, billImpl.GetMaxBillNo());//获得 单号
            return GetNextNO(SystemConfig.CheckBillNOFormate);
        }
        /// <summary>
        /// 出库单单号生成
        /// </summary>
        /// <returns></returns>
        public string CreateOutNextNO()
        {
            //IProductOutService billImpl = ServiceLocator.Instance.GetService<IProductOutService>();
            //return CreateBillNO(SystemConfig.OutBillNOFormate, billImpl.GetMaxBillNo());//获得 单号
            return GetNextNO(SystemConfig.OutBillNOFormate);
        }
        /// <summary>
        /// 销售退货单号生成
        /// </summary>
        /// <returns></returns>
        public string CreateSaleReturnNextNO()
        {
            //IProductReturnBillService billImpl = ServiceLocator.Instance.GetService<IProductReturnBillService>();
            //return CreateBillNO(SystemConfig.SaleReturnBillNOFormate, billImpl.GetMaxBillNo());//获得 单号
            return GetNextNO(SystemConfig.SaleReturnBillNOFormate);
        }
        /// <summary>
        ///损溢报告单号生成
        /// </summary>
        /// <returns></returns>
        public string CreateProfitAndLossNextNO()
        {
            //IProfitAndLossBillService billImpl = ServiceLocator.Instance.GetService<IProfitAndLossBillService>();
            //return CreateBillNO(SystemConfig.ProfitAndLossBillNOFormate, billImpl.GetMaxBillNo());//获得 单号

            return GetNextNO(SystemConfig.ProfitAndLossBillNOFormate);
        }
        /// <summary>
        ///退货单号生成
        /// </summary>
        /// <returns></returns>
        public string CreateReturnNextNO()
        {
            //IReturnBillService billImpl = ServiceLocator.Instance.GetService<IReturnBillService>();
            //return CreateBillNO(SystemConfig.ReturnBillNOFormate, billImpl.GetMaxBillNo());//获得 单号

            return GetNextNO(SystemConfig.ReturnBillNOFormate);
        }

        /// <summary>
        ///调拔单号生成
        /// </summary>
        /// <returns></returns>
        public string CreateAllotNextNO()
        {
            //IProductAllotService billImpl = ServiceLocator.Instance.GetService<IProductAllotService>();
            //return CreateBillNO(SystemConfig.AllotNOFormate, billImpl.GetMaxBillNo());//获得 单号
            return GetNextNO(SystemConfig.AllotNOFormate);
        }
        /// <summary>
        /// 工资单号(批次)生成
        /// </summary>
        /// <returns></returns>
        public string CreateWageNextNO()
        {
            //IWorkGroupService billImpl = ServiceLocator.Instance.GetService<IWorkGroupService>();
            //return CreateBillNO(SystemConfig.WagesBillNO, billImpl.GetMaxBillNo());//获得 单号
            return GetNextNO(SystemConfig.WagesBillNO);
        }
        #region 通用单号生成
        private string GetNextNO(string dhType)
        {
            string nextNo = "";
            lock (obj)
            {
                nextNo = CreateBillNO(dhType, billImpl.GetNextBuessionDh(dhType, "", false));//获得 单号
                billImpl.GetNextBuessionDh(dhType, nextNo, true);
            }
            return nextNo;
        }

        /// <summary>
        /// 获得 单号
      /// </summary>
      /// <param name="billFormat">单号起始部分：如：（发货：FH）</param>
      /// <param name="dbMaxBillNo">该单据存在数据库中的最大单号</param>
      /// <returns>最单号</returns>
        private  string CreateBillNO(string billFormat,string dbMaxBillNo)
        {
            string newNo = string.Empty;
            string no = dbMaxBillNo;
            if (string.IsNullOrEmpty(no))
            {
                newNo= InitNo(billFormat);
            }
            else
            {
                string m = "", firstNo = "";
                if (SystemConfig.BuinessBillNOHasSplit)
                {
                    m = no.Substring(no.LastIndexOf(SystemConfig.BuinessBillNOSplitChar) + 1, no.Length - no.LastIndexOf(SystemConfig.BuinessBillNOSplitChar) - 1);
                    firstNo = no.Substring(0, no.IndexOf(SystemConfig.BuinessBillNOSplitChar) - 1);
                }
                else
                {
                    m = no.Substring(no.Length - SystemConfig.BuinessBillNOLength, SystemConfig.BuinessBillNOLength);
                    firstNo = no.Substring(0, no.Length - SystemConfig.BuinessBillNOLength - 6-2);//日期占6位
                }

                #region 若日期不同，则从第一号开始
                var oldData = no.Replace(m, "").Replace(firstNo, "");
                if (oldData != DateTime.Now.ToString("yyyyMMdd"))
                {
                    newNo = InitNo(billFormat).Replace(SystemConfig.BuinessBillNOSplitChar,"");
                    return newNo;//返回
                }
                #endregion

                if (firstNo != billFormat)
               {
                   newNo = InitNo(billFormat);
               }
               else
               {
                   var k = Convert.ToInt32(m) + 1;
                   var lastNo = string.Format("{0:" + InitLastNo() + "0}", k);
                   newNo = no.Replace(m, lastNo);
               }
            }
            if (!SystemConfig.BuinessBillNOHasSplit)
            {
               newNo= newNo.Replace(SystemConfig.BuinessBillNOSplitChar, "");
            }
            return newNo;
        }
        /// <summary>
        /// 初始化单号（第一次生成单号）
        /// </summary>
        /// <param name="billNoFormat">根据单据类别（前辍）</param>
        /// <returns></returns>
        private string InitNo(string billNoFormat)
        {
            return string.Format(SystemConfig.BuinessBillNOFormate,
                   SystemConfig.BuinessBillNOSplitChar,
                   billNoFormat,
                   DateTime.Now.ToString("yyyyMMdd"),
                   InitLastNo() + "1"
                   );
        }
       /// <summary>
       /// 根据配置文件
       /// </summary>
       /// <returns>根据配置文件的生成每天单号位数（如：5表示最大支持99999笔订单）</returns>
        private string InitLastNo()
        {
            string str = "";
           
            for (int i = 0; i < SystemConfig.BuinessBillNOLength-1; i++)
            {
                str += "0";
            }
            return str;
        }

        #endregion
    }
}
